#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import pymongo


def recursive_head_lineage(name: str, collection: pymongo.collection.Collection):
    lineage = [name]
    current_name = name
    while current_name != "Viruses":
        current_name = parent_taxon_name(current_name, collection)
        print(current_name)
        if current_name is None:
            return None, None
        lineage.append(current_name)
    lineage = lineage[-2::-1]
    head = lineage[0]
    lineage = "; ".join(lineage)
    return head, lineage


def parent_taxon_name(name: str, collection: pymongo.collection.Collection):
    result = collection.find_one({"dms_name": name}, {"dms_id": 1, "parent_tax_id": 1})
    if result is None:
        return None
    else:
        result2 = collection.find_one({"dms_id": result["parent_tax_id"]["id"]}, {"dms_name": 1})
        return result2["dms_name"]


if __name__ == '__main__':
    client = pymongo.MongoClient("10.188.188.22", 27017)
    db = client["Dictionary"]
    collection = db["taxonomy_20200202"]

    head, lineage = recursive_head_lineage("Boiling Springs Lake RNA-DNA hybrid virus", collection)
    print(head)
    print(lineage)
    client.close()
